package com.start.common.dataRule;

import com.start.common.enums.StartBaseStringEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 数据规则条件
 */
public enum DataRuleConditionEnum implements DataRuleConditionKey, StartBaseStringEnum {


    EQ("等于", "eq"),

    GT("大于", "gt"),

    GE("大于等于", "ge"),

    LT("小于", "lt"),

    LE("小于等于", "le"),

    NE("不等于", "ne"),

    BETWEEN("之间", "between"),

    NOT_BETWEEN("不在之间", "not_between"),

    LIKE("全模糊", "like"),

    NOT_LIKE("不包含模糊内容", "no_like"),

    LIKE_LEFT("左模糊", "like_left"),

    LIKE_RIGHT("右模糊", "like_right"),

    IN(" in ", "in"),

    NOT_IN(" not in ", "not_in"),

    IS_NULL("是 null", "is_null"),

    IS_NOT_NULL("不是 null", "is_not_null"),

    CUSTOM_SQL("自定义sql", "custom_sql"),

    ORDER_BY_ASC("排序正序", "asc"),

    ORDER_BY_DESC("排序倒序", "desc");


    private String label;

    private String value;



    DataRuleConditionEnum(String title, String value) {
        this.label = title;
        this.value = value;

    }

    public String getLabel() {
        return label;
    }

    public String getValue() {
        return value;
    }




    public static DataRuleConditionEnum create(String code) {
        for (DataRuleConditionEnum conditionEnum : DataRuleConditionEnum.values()) {
            if (Objects.equals(code, conditionEnum.getValue())) {
                return conditionEnum;
            }
        }
        return null;
    }

    /**
     * 条件匹配表达式
     */
    public static final String variableExpressionRegexStr = "^\\#\\{\\w+\\}";
    public static final Pattern variableExpressionRegexPattern = Pattern.compile(variableExpressionRegexStr);

    public static DataRuleConditionEnum getRuleCondition(String[] values) {
        return getRuleCondition(values, 0);
    }

    public static DataRuleConditionEnum getRuleCondition(String[] values, int i) {
        if (values == null || values.length < 1) return null;
        if (i < 0 || i > values.length - 1) return null;
        DataRuleConditionEnum conditionEnum = null;
        if (StringUtils.isEmpty(values[i])) return null;
        Matcher variableMatcher = variableExpressionRegexPattern.matcher(values[i]);
        while (variableMatcher.find()) {
            String group = variableMatcher.group();
            conditionEnum = create(group.replace("#", "").replace("{", "").replace("}", ""));
            values[i] = values[i].replace(group, "");
        }
        return conditionEnum;
    }
}
